package com.gltqe.dict;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * 自定义 Jackson序列化器
 *
 * @author gltqe
 * @date 2023/6/14 15:03
 **/
public class DictSerializer extends JsonSerializer<Object> {

    private Dict dict;

    private DictHandle dictHandle;

    public DictSerializer(DictHandle dictHandle) {
        this.dictHandle = dictHandle;
    }

    /**
     * 序列化
     *
     * @author gltqe
     * @date 2023/6/15 16:20
     **/
    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

        if (dict != null && o != null) {
            // 写入原值
            jsonGenerator.writeObject(o);

            // 获取字典
            Object content = getDictContent(dict, String.valueOf(o));

            // 获取当前字段名字
            String fieldName = jsonGenerator.getOutputContext().getCurrentName();

            // 获取新字段名
            fieldName = fieldName.concat(dictHandle.getSuffix());

            // 写入一个新字段
            jsonGenerator.writeObjectField(fieldName, content);
        }
    }

    /**
     * 设置字典
     *
     * @param dict
     * @author gltqe
     * @date 2023/6/15 15:58
     **/
    public void setDict(Dict dict) {
        this.dict = dict;
    }

    /**
     * 获取字典的内容
     *
     * @param dict       字典
     * @param fieldValue 字段值
     * @return: java.lang.Object
     * @author gltqe
     * @date 2023/6/15 15:52
     **/
    public Object getDictContent(Dict dict, String fieldValue) {
        if ("".equals(dict.dictMap()) && "".equals(dict.dictCode())) {
            return null;
        }
        if ("".equals(dict.dictMap().trim())) {
            return dictHandle.getDictContent(dict, fieldValue);
        } else {
            String converter = dict.dictMap();
            String[] dictPairs = converter.split(dict.sepDict());
            for (String dictPair : dictPairs) {
                String[] keyValue = dictPair.split(dict.sepPair());
                if (fieldValue.equals(keyValue[0])) {
                    return keyValue[1];
                }
            }
            return null;
        }
    }

    /**
     * 获取字典处理器
     *
     * @return: org.gltqe.dict.DictHandle
     * @author gltqe
     * @date 2023/6/16 9:49
     **/
    public DictHandle getDictHandle() {
        return dictHandle;
    }

}
